package com.bw.a2209clubshop.myview

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.ViewGroup

class MyViewGroup : ViewGroup {
    constructor(context: Context) : this(context,null)
    constructor(context: Context, attrs: AttributeSet?):this(context,attrs,0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int):this(context,attrs,defStyleAttr,0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int):super(context,attrs,defStyleAttr,defStyleRes)
    private var oritation:Int=0
    private var parentWidth=0
    private var parentHeight=0
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        measureChildren(widthMeasureSpec,heightMeasureSpec)
        parentWidth=MeasureSpec.getSize(widthMeasureSpec)
        parentHeight=MeasureSpec.getSize(heightMeasureSpec)
        Log.d("MyViewGroup", "width："+parentWidth)
        Log.d("MyViewGroup", "height："+parentHeight)
        setMeasuredDimension(parentWidth,parentHeight)
    }

    private var width=0
    private var height=0

    override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {
        for (i in 0 until childCount){
            val view = getChildAt(i)
            if (oritation==0){
                Log.d("MyViewGroup", "parentwidth："+parentWidth)
                Log.d("MyViewGroup", "parentheight："+parentHeight)
                Log.d("MyViewGroup", "width："+width)
                Log.d("MyViewGroup", "height："+height)
                if (width+view.measuredWidth>parentWidth || width+view.measuredWidth==parentWidth){
                    width=0
                    height+=view.measuredHeight
                }
                view.layout(width,height,width+view.measuredWidth,height+view.measuredHeight)
                width+=view.measuredWidth

            }else{
                if (height+view.measuredHeight>parentHeight || height+view.measuredHeight==parentHeight){
                    height=0
                    width+=view.measuredWidth
                }
                view.layout(width,height,view.measuredWidth,height+view.measuredHeight)
                height+=view.measuredWidth
            }

        }
    }

}